package ar.com.e2solver.model;

import java.awt.Color;

import ar.com.e2solver.conf.PuzzleTheme;

public class Piece {

	public static Color BORDER_COLOR = Color.GRAY;
	private Color[] colors = new Color[4];
	private Integer number;
	private Integer borders;
	
	public Piece(Color left, Color top, Color right, Color bottom, Integer number){
		this.colors[0] = left;
		this.colors[1] = top;
		this.colors[2] = right;
		this.colors[3] = bottom;
		this.number = number;
		this.borders = countBorders();
	}

	public Piece(Piece piece) {
		this.colors[0] = piece.getLeft();
		this.colors[1] = piece.getTop();
		this.colors[2] = piece.getRight();
		this.colors[3] = piece.getBottom();
		this.number = piece.getNumber();
		this.borders = countBorders();
	}
	
	public void rotateToRight(int times){
		for(int i = 0; i < times; i++){
			Color tmp0 = this.colors[0];
			Color tmp1 = this.colors[1];
			Color tmp2 = this.colors[2];
			Color tmp3 = this.colors[3];
			
			this.colors[0] = tmp3;
			this.colors[1] = tmp0;
			this.colors[2] = tmp1;
			this.colors[3] = tmp2;
		}
	}
	
	public Color getLeft(){
		return this.colors[0];
	}
	
	public Color getTop(){
		return this.colors[1];
	}
	
	public Color getRight(){
		return this.colors[2];
	}
	
	public Color getBottom(){
		return this.colors[3];
	}
	
	public Integer getNumber() {
		return this.number;
	}
	
	public boolean isABorderPiece(){
		return this.borders == 1;
	}
	
	public boolean isACornerPiece(){
		return this.borders >= 2;
	}
	
	private int countBorders(){
		int cantBorders = 0;
		if(this.getLeft().equals(Piece.BORDER_COLOR)){
			cantBorders++;
		}
		if(this.getTop().equals(Piece.BORDER_COLOR)){
			cantBorders++;
		}
		if(this.getRight().equals(Piece.BORDER_COLOR)){
			cantBorders++;
		}
		if(this.getBottom().equals(Piece.BORDER_COLOR)){
			cantBorders++;
		}
		return cantBorders;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(!this.getClass().equals(obj.getClass())){
			return false;
		}
		Piece thePiece = (Piece) obj;
		return thePiece.getNumber().equals(this.getNumber());
	}
	
	@Override
	public int hashCode() {
		return	this.getNumber().hashCode();
	}
	
	public boolean equalPositionAndColor(Piece thePiece){
		return 	thePiece != null &&
				this.getNumber().equals(thePiece.getNumber()) &&
				this.getLeft().equals(thePiece.getLeft()) && 
				this.getTop().equals(thePiece.getTop()) &&
				this.getRight().equals(thePiece.getRight()) &&
				this.getBottom().equals(thePiece.getBottom());
		
	}
	
	@Override
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(PuzzleTheme.getNumberForColor(this.getTop()));
		sb.append(" ");
		sb.append(PuzzleTheme.getNumberForColor(this.getRight()));
		sb.append(" ");
		sb.append(PuzzleTheme.getNumberForColor(this.getBottom()));
		sb.append(" ");
		sb.append(PuzzleTheme.getNumberForColor(this.getLeft()));
		
		return sb.toString();
	}
	
}
